package com.example.mouther_bg.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.mouther_bg.utils.JWTUtils;
import com.example.mouther_bg.utils.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null ){
            Result.tokenErr(500,"token不存在");
            return false;
        }
        try {
            JWTUtils.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            Result.tokenErr(500,"无效签名");
            e.printStackTrace();
        } catch (TokenExpiredException e){
            Result.tokenErr(500,"token过期");
            e.printStackTrace();
        } catch (AlgorithmMismatchException e){
            Result.tokenErr(500,"token算法不一致");
            e.printStackTrace();

        } catch (Exception e){
            Result.tokenErr(403,"token不存在或无效");
            e.printStackTrace();
        }
        return false;
    }
}
